package com.jlnk.touchdemo.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.jlnk.touchdemo.R;

public class SignatureView extends View {
    private Path mPath = new Path();
    private Paint mPaint = new Paint();
    private Canvas mCanvas;
    private Bitmap mCacheBitmap;
    private Context mContext;

    public SignatureView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(10);
        mPaint.setColor(Color.BLACK);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mCacheBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mCacheBitmap);
        mCanvas.drawColor(Color.WHITE);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float strokeWidth = mPaint.getStrokeWidth();
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_POINTER_DOWN:
                for (int i = 0; i < event.getPointerCount(); i++) {
                    float x = event.getX(i);
                    float y = event.getY(i);
                    mPath.moveTo(x, y);
                }
                break;
            case MotionEvent.ACTION_MOVE:
                for (int i = 0; i < event.getPointerCount(); i++) {
                    float x = event.getX(i);
                    float y = event.getY(i);
                    mPath.lineTo(x, y);
                    mCanvas.drawPath(mPath, mPaint);
                    mPath.reset();
                    mPath.moveTo(x, y);
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                break;
        }
        invalidate();
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(mCacheBitmap, 0, 0, null);
        canvas.drawPath(mPath, mPaint);
    }

    public void clear() {
        mPath.reset();
        mCanvas.drawColor(Color.WHITE);
        invalidate();
    }

    public void saveImageToGallery() {
        // 保存 mCacheBitmap 到图库
        String savedImageURL = MediaStore.Images.Media.insertImage(
                mContext.getContentResolver(),
                mCacheBitmap,
                "testSign",
                "testSign save"
        );
        Toast.makeText(mContext, "保存成功! URL:" + savedImageURL, Toast.LENGTH_SHORT).show();
    }
}